'''
Created on 2009-9-16

@author: loudly
'''
from django.newforms.util import *
from django import newforms as forms

class MultipleTextInputWidget(forms.MultiWidget): 
    
    divAttrs = {}
    inputAttrs = {}
    
    def __init__(self, numberOfInputs, attrs = None):
        self.numberOfInputs = numberOfInputs 
        widgets = (forms.TextInput(),) * numberOfInputs
         
        super(MultipleTextInputWidget, self).__init__(widgets = widgets, attrs = attrs)
         
    def decompress(self, value): 
        ret = [None] * self.numberOfInputs
        
        if isinstance(value, (list, tuple)) :
            i = 0
            for v in value :
                ret[i] = v
                i += 1
                if i >= self.numberOfInputs : break
        
        return ret
    
    def render(self, name, value, divAttrs = None, attrs = None):
        """
        value is a list of values, each corresponding to a widget
        in self.widgets.
        The two attrs:
        <div divAttrs><input type='bla' attrs></div>
        """
        if attrs == None : 
            attrs = {}
        attrs.update(self.inputAttrs)
        
        if divAttrs == None : 
            divAttrs = {}
        divAttrs.update(self.divAttrs)
        
        if not isinstance(value, list):
            value = self.decompress(value)
        output = []
        for i, widget in enumerate(self.widgets):
            try:
                widget_value = value[i]
            except KeyError:
                widget_value = None
            
            div = ''
            div += '<div %s >' % flatatt(divAttrs)
            div += widget.render(name + '_%s' % i, widget_value, attrs)
            div += '</div>'
            div += '\n'
            
            output.append(div)
            
        return self.format_output(output)

class MultipleCharField(forms.MultiValueField): 
    
    def __init__(self, numberOfFields, **kwargs):
        #fields 
        fields = []
        for i in range(0, numberOfFields) :
            fields.append(forms.CharField())
        fields = tuple(fields)
         
        super(MultipleCharField, self).__init__(fields, **kwargs)
        
        self.widget = MultipleTextInputWidget(numberOfFields)
    
    def compress(self, data_list): 
        return data_list
    